/* jslint unused: false */
/* global $, _, motify, console, alert, wxReady, WeixinJSBridge, initImagePre */
(function($, window, document, undefined) {

    'use strict';

    var EC = window.EC = $(document);
    var global = window._global;

    // 工具类
    var Utils = window.Utils || {};

    // 扩展工具类
    $.extend(Utils, {
        // 获取最近使用的地址
        getRecentlyUsedAddress: function() {
            var address = false;
            if ( !! window.localStorage) {

                var str = $.trim(window.localStorage.getItem('recently_used_address'));

                if (str.indexOf('undefined') !== -1) {
                    // 如果地址中存在 undefined 则删除本地存储的地址，并将 str 设置为空字符串
                    window.localStorage.removeItem('recently_used_address');
                    str = '';
                }

                if (str) {
                    try {
                        motify.log('读取最近使用的收货地址中...');
                        address = $.parseJSON(str);
                    } catch (e) {

                    }
                }
            }
            return address;
        },

        // 存储最近使用的地址到本地存储
        saveLastUsedAddress: function(address) {
            if (!address || !address.userName) {
                return false;
            }

            var addressStr = JSON.stringify(address);

            if ( !! window.localStorage) {
                window.localStorage.setItem('recently_used_address', addressStr);
            }
        },

        // 转换地址参数wx to kdt
        wx2KdtAddress: function(data) {

            if (!data.userName && data.user_name) {
                return data;
            }
            // wx to kdt
            var address = {
                user_name: data.userName,
                province: data.proviceFirstStageName,
                city: data.addressCitySecondStageName,
                county: data.addressCountiesThirdStageName,
                address_detail: data.addressDetailInfo,
                tel: data.telNumber,
                postal_code: data.addressPostalCode
            };

            return address;
        },

        // 转换地址参数kdt to wx
        kdt2WxAddress: function(data) {

            if (!data.user_name && data.userName) {
                return data;
            }
            // kdt to wx
            var address = {
                userName: data.user_name,
                proviceFirstStageName: data.province,
                addressCitySecondStageName: data.city,
                addressCountiesThirdStageName: data.county,
                addressDetailInfo: data.address_detail,
                telNumber: data.tel,
                addressPostalCode: data.postal_code
            };

            return address;
        },

        // 获取干净的地址数据
        getPureAddressData: function(res) {
            if (!res || !res.userName) {
                return false;
            }

            var address = {
                userName: res.userName,
                proviceFirstStageName: res.proviceFirstStageName,
                addressCitySecondStageName: res.addressCitySecondStageName,
                addressCountiesThirdStageName: res.addressCountiesThirdStageName,
                addressDetailInfo: res.addressDetailInfo,
                telNumber: res.telNumber,
                addressPostalCode: res.addressPostalCode
            };

            return address;
        },

        // 更新完地址后的动画效果
        flashAnimate: function(ele) {
            ele.addClass('animated flashWarn');

            window.setTimeout(function() {
                ele.removeClass('flashWarn');
            }, 1000);
        },

        // 需要用户再次确认
        needConfirm: function(msg, yesClk, noClk) {

            var result = window.confirm(msg);

            if (result) {
                if (yesClk && typeof yesClk === 'function') {
                    yesClk.apply();
                }
            } else {
                if (noClk && typeof noClk === 'function') {
                    noClk.apply();
                }
            }
        },

        // 获取模版
        getTpl: function(selector) {
            var tplEle = $(selector);
            if (tplEle) {
                return _.template(tplEle.html());
            }
        },

        validMobile: function(value) {
            value = '' + value;
            return /^((\+86)|(86))?(1)\d{10}$/.test(value);
        },

        validPhone: function(value) {
            value = '' + value;
            return /^0[0-9\-]{10,13}$/.test(value);
        },

        validPostalCode: function(value) {
            value = '' + value;
            return /[1-9]\d{5}(?!\d)/.test(value);
        }

    });

    // Create the defaults once
    var klassName = 'OrderConfirm',
        defaults = {
            baseUrl: global.wxpay_env ? global.url.trade : global.url.wdp_wap,
            orderState: global.order_state || 1,
            requiredAddress: global.is_virtual === '0' ? true : false,
            permissions: {
                wxAddress: global.wxaddress_env,
                wxPay: global.wxpay_env,
                aliPay: global.alipay_env
            },
            emptyAddress: {
                user_name: '',
                province: '',
                city: '',
                county: '',
                area_code: '',
                address_detail: '',
                postal_code: '',
              tel: '',
            }
        };

    function Klass(options) {

        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = klassName;
        this.init();
    }

    Klass.prototype = {
        init: function() {
            var self = this;

            self.hasAddress = 0;

            self.debug();

            self.wxUi();

            self.findEle();

            self.initTpl();

            self.initCountdown();

            self.initReselect();

            self._init();

            self.initCoupon();

            self.initPayOrder();
        },

        wxUi: function() {
            $('.wap-page-order').removeClass('hide');
            // 根据配置参数是否隐藏微信内置底部栏
            if (global.js.hide_wx_nav) {
                wxReady(function() {
                    WeixinJSBridge.call('hideOptionMenu');
                    WeixinJSBridge.call('hideToolbar');
                });
            } else {
                wxReady(function() {
                    WeixinJSBridge.call('showOptionMenu');
                    WeixinJSBridge.call('showToolbar');
                });
            }
        },

        debug: function() {
            // 如果需要清理本地存储的收货地址则移除本地存储里的 recently_used_address
            if (!! window.localStorage && global.clear_local_address) {
                window.localStorage.removeItem('recently_used_address');
            }
        },

        findEle: function() {
            var self = this;

            self.bodyEle = $('body');
            self.pageContent = $('.js-page-content');
            self.contentEle = self.pageContent.find('.content');
            self.footerEle = $('.footer');

            self.countEle = $('.js-mini-counter');
            self.countMsg = $('.js-counter-msg');

            self.btnReselect = $('.js-reselect-model');

            self.addressTip = $('.js-address-tip');
            self.btnChangeAddress = $('.js-change-address');
            self.choosedAddressContainer = $('#js-address-detail');

            self.modalEle = $('.js-modal');
            self.addAddressEle = $('.js-add-address');
            self.addressContainer = $('.js-address-container');
            self.sceneAddressFm = $('.js-scene-address-fm');

            self.useCouponEle = $('.js-used-coupon');
            self.couponContainer = $('.js-coupon-container');

            self.orderTotalEle = $('.js-order-total');
            self.realPayEle = $('.js-real-pay');

            self.stepPay = $('.js-step-topay');
            self.wxPayBtn = $('.js-wx-pay');
            self.aliPayBtn = $('.js-ali-pay');
            self.payTip = $('.pay-tip');
        },

        initTpl: function() {
            var self = this;

            self.addressItemTpl = Utils.getTpl('#tpl-address-item');
            self.addressFmTpl = Utils.getTpl('#tpl-address-fm');
            self.orderAddressTpl = Utils.getTpl('#tpl-order-address');

            self.couponItemTpl = Utils.getTpl('#tpl-coupon-item');
            self.useCouponTpl = Utils.getTpl('#tpl-use-coupon');
            self.availableCouponTpl = Utils.getTpl('#tpl-available-coupon');
            self.orderTotalTpl = Utils.getTpl('#tpl-order-total');

            self.aliFormTpl = Utils.getTpl('#tpl-ali-form');
        },

        _init: function() {
            var self = this;
 
            var o = self.settings;
           
            // 正则匹配微信版本
            var ua = window.navigator.userAgent;
            var wxCheck = ua.match(/MicroMessenger\/(\d+(\.\d+)*)/);
            var isWx = wxCheck !== null && wxCheck.length;
            var wxVer = (isWx) ? parseFloat(wxCheck[1]) : 0;

            // @DEBUG
            // isWx = true;
            // wxVer = 5.2;

            if (!isWx) {
                // 非微信

                self.initKdtAddress();
                self.initAliPay();

            } else if (wxVer < 5) {
                // 是微信且微信版本小于5

                // 仅在微信浏览器中处理图片(@trade/base)
                self.initWxImage();
                self.initKdtAddress();
                self.initAliPay();

            } else {
                // 微信版本 >= 5.0

                self.initWxImage();

                if (o.permissions.wxAddress) {
                    self.initWxAddress();
                } else {
                    self.initKdtAddress();
                }

                if (o.permissions.wxPay) {
                    self.initWxPay();
                } else {
                    self.initAliPay();
                }

            }
        },

        // 初始化微信内置浏览器预览图片效果
        initWxImage: function() {
            var self = this;

            console.log('initWxImage');

            // 仅在微信浏览器中处理图片(@trade/base)
            wxReady(function() {
                initImagePre();
            });
        },

        initWxAddress: function() {
            var self = this;

            console.log('initWxAddress');

            // 修改收货地址
            wxReady(function() {
                EC.on('wx_address', function() {

                    console.log('EC:wx_address');
                    // alert('EC:wx_address');
                    // alert(JSON.stringify(global.address_token));

                    if (self.isOpened) {
                        return false;
                    }

                    // self.isOpened = true;

                    WeixinJSBridge.invoke('editAddress', global.address_token, function(res) {

                        var err_msg = res.err_msg;

                        self.isOpened = false;
                        self.bodyEle.removeClass('to-address');
                        self.pageContent.removeClass('hide');

                        // 获取最近使用的地址成功
                        if (err_msg == 'edit_address:ok') {

                            // motify.log('更新订单收货地址中...');
                            var _address = Utils.getPureAddressData(res);
                            Utils.saveLastUsedAddress(_address);
                            self.saveAddress(_address, 'wx');

                        } else if (err_msg == 'edit_address:fail') {

                        } else {

                        }
                    });

                });

                // 读取本地存储中的地址
                self.readLocalAddress('wx');
            });

            // 修改地址
            self.btnChangeAddress.on('tap', function(event) {
                event.preventDefault();
                event.stopPropagation();

                EC.trigger('wx_address');
            });

            // 修改地址的tip
            self.addressTip.on('tap', function(event) {
                event.preventDefault();

                EC.trigger('wx_address');
            });
        },

        /**
         * 读取本地存储中的地址
         * @param  {string} payType 地址类型
         */
        readLocalAddress: function(payType) {
            var self = this;

            var orderState = global.order_state;
            if (orderState === 1) {
                if (self.settings.requiredAddress) {
                    // 实物商品

                    var address = Utils.getRecentlyUsedAddress();

                    if (address) {
                        address = Utils.wx2KdtAddress(address);
                        self.bodyEle.removeClass('to-address');
                        self.pageContent.removeClass('hide');
                        self.addressTip.find('span').text('读取地址中...');
                        self.saveAddress(address, payType);
                    } else {
                        EC.trigger(payType + '_address');
                    }

                } else {
                    // 虚拟商品

                    self.bodyEle.removeClass('to-address');
                    self.pageContent.removeClass('hide');

                }
            }
        },

        initWxPay: function() {
            var self = this;

            console.log('initWxPay');

            self.wxPayBtn.show();
            // 调出微信支付
            EC.on('wx_pay', function(event, payData) {

                // 支付相关数据
                console.log('EC:wx_pay', JSON.stringify(payData));

                if (self.isOpened) {
                    return false;
                }

                // self.isOpened = true;

                // 如果传入的参数为字符串类型，则尝试转换为JSON
                if (typeof payData === 'string') {
                    payData = $.parseJSON(payData);
                }

                // 禁用微信安全支付按钮
                self.wxPayBtn.prop('disabled', true);
                self.wxPayBtn.html('等待支付...');

                // 调用微信安全支付
                WeixinJSBridge.invoke('getBrandWCPayRequest', payData, function(res) {

                    var msg = res.err_msg;

                    self.isOpened = false;

                    if (msg === 'get_brand_wcpay_request:ok') {

                        motify.log('支付成功，正在处理订单...', 0);

                        // 支付成功后页面跳转
                        window.location.href = global.url.trade + '/trade/order/result?order_id=' + global.order_id + '&order_paid=1#wechat_webview_type=1&refresh';

                    } else if (msg === 'get_brand_wcpay_request:fail') {

                        motify.log('支付失败，请重新尝试！');
                        self.wxPayBtn.prop('disabled', false);
                        self.wxPayBtn.html('微信安全支付');

                    } else {

                        motify.clear();
                        self.wxPayBtn.prop('disabled', false);
                        self.wxPayBtn.html('微信安全支付');

                    }
                });
            });

            self.wxPayBtn.on('tap', function(event) {
                event.preventDefault();

                var ele = $(this);

                if (ele.prop('disabled')) {
                    return false;
                }

                var state = ele.data('order-state');

                console.log('wxPayBtn state: ', state);

                if (state === 'address') {
                    if (self.validOrder('wx')) {
                        ele.data('order-state', 'topay');
                        EC.trigger('pay_order', 'wx');
                    }
                } else if (state === 'topay') {
                    EC.trigger('pay_order', 'wx');
                }
            });
        },

        renderAddressFm: function(address) {
            var self = this;

            console.log('renderAddressFm: ', JSON.stringify(address));
            self.sceneAddressFm.html(self.addressFmTpl(address));

            self.addressFm = $('.js-address-fm');
            self.initPCC(address.area_code);
            self.btnSaveAddress = $('.js-address-save');
        },

        initPCC: function(dfCode) {
            var self = this;

            var options = {
                provinceId: 'province',
                cityId: 'city',
                countyId: 'county',
                backCodeId: 'js-df-code'
            };
            if (dfCode) {
                options.dfCode = dfCode;
            }
            $.fn.cityTools(options);
        },

        initKdtAddress: function() {
            var self = this;

            console.log('initKdtAddress');

            self.bodyEle.removeClass('to-address');

            self.isAddressLoaded = false;

            EC.on('kdt_address', function() {
                console.log('EC:kdt_address');

                self.showKdtAddress();
                // self.kdtAddressList();
            });

            // 读取本地存储中的地址
            self.readLocalAddress('kdt');

            // 修改地址
            self.btnChangeAddress.on('tap', function(event) {
                event.preventDefault();
                event.stopPropagation();

                EC.trigger('kdt_address');
            });

            // 修改地址的tip
            self.addressTip.on('tap', function(event) {
                event.preventDefault();

                EC.trigger('kdt_address');
            });

            self.modalEle.on('tap', '.js-add-address', function(event) {
            	
                event.preventDefault();

                self.renderAddressFm(self.settings.emptyAddress);
                self.switchScene('address-fm');
            });

            self.modalEle.on('tap', '.js-address-item', function(event) {
            	
                event.preventDefault();

                var ele = $(this);
                
               
                var address = ele.data('address');
           
                
                var orderno= window._global.order_no;
                var baseUrl = window._global.baseurl;
               
                   $.ajax({  
                    url: baseUrl+'/index.php?r=buyer/UpdateOrderAddress',
                    type: 'Post',
                    data:{'order_no':orderno,'address':address},
                    dataType: 'json',
                    beforeSend: function() {
                    	
                    	
                    },
                    success: function(resp) {
                    	
                    	if(resp.code==0){
                    		
                    		   if (typeof address === 'string') {
                                   address = $.parseJSON(address);
                               }
                               
                            self.selectedAddress(address);
                    		
                    	}else{
                    		
                    		motify.log('地址错误,请重新选择');
                    		
                    	}
                  
                    },
                    error: function(xhr, errorType, error) {
                    
                    
                    },
                    complete: function(xhr, status) {
                    	
                    }
                });
                
                   
                
            });

            self.modalEle.on('tap', '.js-address-save', function(event) {
                event.preventDefault();

                var ele = $(this);
                if (ele.prop('disabled')) {
                    return false;
                }
                self.saveEdit();
            });

            self.modalEle.on('tap', '.js-address-cancel', function(event) {

                self.cancelEdit();
            });

            self.modalEle.on('tap', '.js-cancel-address-list', function(event) {

                self.hideModal();
            });

            self.modalEle.on('tap', '.js-edit-address', function(event) {
                event.preventDefault();
                event.stopPropagation();

                var ele = $(this);
                var item = ele.parents('.js-address-item');
                var address = item.data('address');

                if (typeof address === 'string') {
                    address = $.parseJSON(address);
                }
                self.renderAddressFm(address);
                self.switchScene('address-fm');

                return false;
            });
        },

        showKdtAddress: function() {
            var self = this;

            // self.isAddressEmpty = true;
            if (self.isAddressLoaded) {
                self.switchScene('address-list');
            } else {
                self.loadAdressList();
            }
        },

        loadAdressList: function() {
        	
        	var baseUrl = window._global.baseurl;
            var self = this;
            if (!self.isAddressLoaded) { //加载收获地址
         
                $.ajax({  // buyer/getaddress
                    url: baseUrl+'/index.php?r=buyer/getaddressList',
                    type: 'GET',
                    dataType: 'json',
                    beforeSend: function() {},
                    success: function(resp) {
                        if (resp.code === 0) {
                        	
                            self.isAddressLoaded = true;
                            self.renderAddressList(resp.data);

                            if (resp.data.length === 0) {
                                self.renderAddressFm(self.settings.emptyAddress);
                                self.switchScene('address-fm');
                            } else {
                                self.switchScene('address-list');
                            }

                        } else {
                            self.renderAddressList([]);
                            motify.log(resp.msg);
                        }
                    },
                    error: function(xhr, errorType, error) {
                    
                        motify.log('地址加载失败。');
                        self.renderAddressList([]);
                        self.switchScene('address-list');
                    },
                    complete: function(xhr, status) {}
                });
            }
        },

        renderAddressList: function(list) {
            var self = this;

            self.addressContainer.empty();
            if (list.length > 0) {
                self.isAddressEmpty = false;
                _(list).each(function(address, index, list) {
                    var item = $(self.addressItemTpl(address));
                    item.data('address', JSON.stringify(address));
                    self.addressContainer.append(item);
                });
            } else {
                self.isAddressEmpty = true;
            }
        },

        initAliPay: function() {
            var self = this;

            console.log('initAliPay');

            self.aliPayBtn.show();
            self.payTip.show();

            EC.on('ali_pay', function(event, payData) {
                console.warn('EC:ali_pay', payData);

                self.submitToAlipay(payData);
            });

            self.aliPayBtn.on('tap', function(event) {
                event.preventDefault();

                var ele = $(this);

                if (ele.prop('disabled')) {
                    return false;
                }
           
                var state = ele.data('order-state');

                console.log('wxPayBtn state: ', state);

                if (state === 'address') {
                    if (self.validOrder('kdt')) {
                        ele.data('order-state', 'topay');
                        EC.trigger('pay_order', 'ali');
                    }
                } else if (state === 'topay') {
                    EC.trigger('pay_order', 'ali');
                }
            });
        },

        submitToAlipay: function(payData) {
            var self = this;

            var form = $(self.aliFormTpl(payData));
            form.submit();
        },

        initPayOrder: function() {
            var self = this;

            console.log('initPayOrder');

            // 生成支付单
            EC.on('pay_order', function(event, payType) {

                console.log('pay_order', payType);

                var orderId = global.order_id || 'ERROR_ORDER_ID';

                self.submitPay({
                    order_id: orderId
                }, payType);
            });
        },

        initCountdown: function() {
            var self = this;

            var orderState = self.settings.orderState;

            // 待付款初始化订单自动取消倒计时
            if (orderState === 3 || orderState === 4) {
                self.countEle.MiniCounter({
                    callback: function(left) {
                        self.countMsg.html('<h3>订单状态：您的订单已取消。</h3><hr /><p class="c-important">您的订单因超时未付款，已经自动取消。</p>');
                    }
                });
            }
        },

        initReselect: function() {
            var self = this;

            console.log('initReselect');

            // 跳转回商品详情页重选sku
            self.btnReselect.on('click', function(event) {
                event.stopPropagation();

                motify.log('处理中...');
            });
        },

        saveAddress: function(address, payType) {
        	
            var self = this;
            var baseUrl = window._global.baseurl;
            var order_id = global.order_id;
            if (!order_id) {
                motify.log('无效订单，请重新下单。', 0);
                return false;
            }

            // 保证地址非空
            if (!address) {
                return false;
            }

            // 构建初步提交数据
            var postData = Utils.wx2KdtAddress(address);

            // 合并提交数据
            postData.order_id = order_id;

            $.ajax({   // orderaddreee
                url: baseUrl+'/index.php?r=buyer/getaddress',
                type: 'POST',
                dataType: 'json',
                timeout: 15000,
                data: postData,
                beforeSend: function() {
                    motify.clear();
                    self.hasAddress = 1;
                    self.addressTip.find('span').html('<strong>保存地址中...</strong>');
                    self.btnChangeAddress.prop('disabled', true).html('保存中...');
                },
                success: function(resp) {
                    console.log('save address success');
                    var code = resp.code;
                    switch (code) {
                        case 0:
                        	
                            self.hasAddress = 2;

                            // 更新页面上的地址显示
                            self.updateAddress(postData);

                            self.wxPayBtn.html('微信安全支付').addClass('butn-secure');

                            break;

                        case 11010:
                            // 下单过程价格发生变动

                            Utils.needConfirm(resp.msg, function() {
                                // motify.log('正在处理中...');
                                self.submitPay({
                                    order_id: order_id,
                                    accept_price: 1
                                }, payType);
                            }, function() {
                                motify.log('正在跳转中...', 0);
                                // 取消下单，跳转回商品详情页
                                window.location.href = global.url.wap + '/showcase/goods?alias=' + global.goods_alias;

                            });
                            break;

                        case 11011:
                            // {11011: 商品已售罄}

                            alert(resp.msg);
                            motify.log('正在跳转中...', 0);
                            window.location.href = global.url.wap + '/showcase/goods?alias=' + global.goods_alias;
                            break;

                        case 11020:
                            // {11020: 该商品无此规格}

                            alert(resp.msg);
                            motify.log('正在跳转中...', 0);
                            window.location.href = global.url.wap + '/showcase/goods?alias=' + global.goods_alias;
                            break;

                        case 11012:
                            // {11012: 商品已下架}
                            // 打开商品页面时未下架，下单过程中商品被下架了

                            alert(resp.msg);
                            motify.log('正在跳转中...', 0);
                            window.location.href = global.url.wap + '/showcase/goods?alias=' + global.goods_alias;
                            break;

                        case 11013:
                            // {11013: 商品已被删除或不存在}
                        case 11022:
                            // {11022: 空订单（无任何商品）}
                        case 11023:
                            // {11023: 无此订单数据，或order_id瞎填}

                            alert(resp.msg);
                            wxReady(function() {
                                WeixinJSBridge.invoke('closeWindow', {});
                            });
                            break;

                        default:
                            motify.log(resp.msg);
                            break;
                    }
                },
                error: function(xhr, errorType, error) {
                    console.log('save address error');
                    motify.log('更新收货地址失败');
                },
                complete: function(xhr, status) {
                    console.log('save address complete');
                    self.btnChangeAddress.prop('disabled', false);
                    self.btnChangeAddress.html('修改');
                }
            });
        },

        updateAddress: function(address) {
            var self = this;

            self.addressTip.hide();
            self.btnChangeAddress.show();
            self.stepPay.show();
            $('.js-edit-address, .js-shipping-fee, .js-hr').show();

            var _html = self.orderAddressTpl(address);

            self.choosedAddressContainer.html(_html);
            Utils.flashAnimate($('.js-order-address'));
        },

        // 校验订单
        validOrder: function(payType) {
            var self = this;

            if (self.settings.requiredAddress) {
                if (self.hasAddress === 0) {
                    EC.trigger(payType + '_address');
                    return false;
                } else if (self.hasAddress === 1) {
                    motify.log('收货地址还在保存中，<br />请稍等...');
                    return false;
                }
            }

            return true;
        },

        checkMoneyLimit: function(payType) {
            var self = this;

            // 0 无需校验
            if (payType !== 'ali') {
                return '0';
            }
            var realPay = Number(self.realPayEle.data('real-pay'));
            if (realPay >= 500 && realPay < 1000) {
                return '1';
            } else if(realPay >= 1000) {
                return '2';
            } else {
                return '3';
            }
        },

        // 提交支付单
        submitPay: function(postData, payType) {
            var self = this;
/*
            var msg = '由于支付宝的额度限制，信用卡可以支付小于500元的订单；借记卡或支付宝余额可以支付小于1000元的订单，是否继续？';
            var _result = self.checkMoneyLimit(payType);
            switch(_result) {
                case '1':
                    Utils.needConfirm(msg, function() {
                        self._submitPay(postData, payType);
                    }, function() {

                    });
                    break;
                case '2':
                    motify.log('支付宝单笔支付最多支持999元', 0);
                    return false;
                    break;
                default:
                    self._submitPay(postData, payType);
                    break;

            }
            */
            
            self._submitPay(postData, payType);
        },

        _submitPay: function(postData, payType) {
            var self = this;

            // alert(JSON.stringify(postData));
            if (global.couponId) {
                postData.coupon_id = global.couponId;
              
            }
            postData.user_ua=navigator.userAgent;
            postData.user_ip=window.user_ip;
          
            
           // alert(JSON.stringify(postData));
            $.ajax({  // TODO
                url: window._global.baseurl+'/index.php?r=/buyer/YeePay',
                type: 'POST',
                dataType: 'json',
                timeout: 15000,
                data: postData,
                beforeSend: function() {
                    motify.log('正在处理订单...', 0);
                    if (payType === 'wx') {
                        self.wxPayBtn.prop('disabled', true)
                            .html('等待付款...');
                    } else if (payType === 'ali') {
                        self.aliPayBtn.prop('disabled', true)
                            .html('等待付款...');
                    }
                },
                success: function(resp) {
                    motify.clear();
                    console.log('submitPay: ', JSON.stringify(resp));

                    var code = resp.code;
                    switch (code) {

                        case 0:
                            window.location.href=resp.pay_url;
                            break;

                        case 11022:
                            // {空订单（无任何商品）}
                        case 404:
                            // {11023: 无此订单数据，或order_id瞎填}

                            alert(resp.msg);
                            wxReady(function() {
                                WeixinJSBridge.invoke('closeWindow', {});
                            });
                            break;
                            
                        case 101:
                            // {11023: 无此订单数据，或order_id瞎填}

                            alert(resp.msg);
                            wxReady(function() {
                                WeixinJSBridge.invoke('closeWindow', {});
                            });
                            break;

                        case 11010:
                            // 下单过程价格发生变动

                            Utils.needConfirm(resp.msg, function() {
                                // motify.log('正在处理中...');
                                postData.accept_price = 1;
                                self.submitPay(postData, payType);
                            }, function() {
                                motify.log('正在跳转中...', 0);

                            });
                            break;

                        default:
                            self.resetBtn(payType);
                            motify.log(resp.msg);
                            break;
                    }
                },
                error: function(xhr, errorType, error) {
                	
                   console.log('error: ', JSON.stringify(xhr));

                    motify.clear();

                    console.log('submit pay order error');
                    motify.log('生成支付单失败。');
                    self.resetBtn(payType);
                },
                complete: function(xhr, status) {
                    motify.log('准备跳转到支付..',15000);
                    // console.log('complete: ', JSON.stringify(xhr));
                    console.log('submit pay order complete');
                }
            });
        },

        resetBtn: function(payType) {
            var self = this;

            if (payType === 'wx') {
                self.wxPayBtn.prop('disabled', false)
                    .html('微信安全支付');
            } else if (payType === 'ali') {
                self.aliPayBtn.prop('disabled', false)
                    .html('易宝支付');
            }
        },

        showCoupons: function(couponId) {
            var self = this;

            console.log('showCoupons: ', couponId);
            if (!self.initCouponFlag) {
                self.renderCouponList(couponId);
            } else {
                self.showSelectdCoupon(couponId);
            }
            self.switchScene('coupon-list');
        },

        autoUseCoupon: function(coupon) {
            var self = this;

            console.log('autoUseCoupon: ', coupon);

            if (coupon.card) {

                self.useCouponFx(coupon);

            }

        },

        switchScene: function(sceneName) {
            var self = this;

            console.log('switchScene: ', sceneName);
            motify.clear();

            // self.hideModal();

            var sceneEles = $('.scene');
            var _c = '.js-scene-' + sceneName;
            sceneEles.filter(_c).removeClass('hide').siblings('.scene').addClass('hide');

            // setTimeout(function() {
            self.showModal();
            // }, 100);
        },

        showModal: function() {
            var self = this;

            window.clearTimeout(self.timer);
            self.timer = null;

            self.contentEle.hide();
            self.footerEle.hide();
            self.modalEle.addClass('active');
        },

        hideModal: function() {
            var self = this;

            self.modalEle.removeClass('active');

            self.timer = window.setTimeout(function() {
                self.contentEle.show();
                self.footerEle.show();
            }, 200);
        },

        selectedAddress: function(address) {
            console.log('selectedAddress', address);
            var self = this;

            if (!address) {
                motify.log('地址选择失败，请重试...');
                return false;
            }

            self.hideModal();

            var _address = Utils.kdt2WxAddress(address);
            Utils.saveLastUsedAddress(_address);
            self.saveAddress(address, 'wx');
        },

        saveEdit: function() {
            var self = this;

            var formData = self.addressFm.serializeArray();

            // var address = _.object(_.pluck(formData, 'name'), _.pluck(formData, 'value'));
            var address = {};
            _.each(formData, function(data, index, list) {
                address[data.name] = data.value;
            });

            console.log('saveEdit: ', JSON.stringify(address));
            self.saveEditToServer(address);
        },

        saveEditToServer: function(address) {
            var self = this;
            var baseUrl = window._global.baseurl;
            // 校验地址数据
            if (!self.validAddress(address)) {
                return false;
            }

            var _url = self.settings.baseUrl,
                _type = 'POST';

            if (address.id) {
                _url = baseUrl+'/index.php?r=buyer/saveaddress';
                
            } else {
                _url = baseUrl+'/index.php?r=buyer/saveaddress';
            }

            $.ajax({   // edit address
                url: _url,
                type: 'post',
                dataType: 'json',
                data: address,
                beforeSend: function() {
                    self.btnSaveAddress.prop('disabled', true).html('保存中...');
                },
                success: function(resp) {
                	
                	
                    if (resp.code === 0) {

                        if (!address.id) {
                            $.extend(address, {
                                id: resp.data.id
                            });
                        }
                        if (self.isAddressEmpty) {
                            self.selectedAddress(address);
                        } else {
                            self.switchScene('address-list');
                        }
                        self.addAddressToList(address);
                        
                        var orderno= window._global.order_no;
                        var baseUrl = window._global.baseurl;
                       
                           $.ajax({  
                            url: baseUrl+'/index.php?r=buyer/UpdateOrderAddress',
                            type: 'Post',
                            data:{'order_no':orderno,'address':JSON.stringify(address)},
                            dataType: 'json',
                            success: function(resp) {},
                            error: function(xhr, errorType, error) {},
                            complete: function(xhr, status) {}
                        });

                    } else {
                        motify.log(resp.msg);
                    }
                },
                error: function(xhr, errorType, error) {
               
                    motify.log('保存地址失败，请稍后重试。');
                },
                complete: function(xhr, status) {
                    self.btnSaveAddress.prop('disabled', false).html('保存');
                }
            });
        },

        addAddressToList: function(address) {
            var self = this;

            self.isAddressEmpty = false;

            var _html = self.addressItemTpl(address),
                ele = $(_html);

            var _id = address.id;

            var item = self.addressContainer.find('#js-address-item-' + _id);
            if (item.length) {
                item.html(ele.html());
            } else {
                item = ele;
                self.addressContainer.prepend(item);
            }
            console.log('addAddressToList: ', address);
            item.data('address', JSON.stringify(address));
        },

        validAddress: function(address) {
            var self = this;

            console.log('validAddress');
            if (!address.user_name) {
                motify.log('请填写名字');
                self.modalEle.find('input[name="user_name"]').focus();
                return false;
            }
            if (!address.address_detail) {
                motify.log('请填写详细地址');
                self.modalEle.find('input[name="address_detail"]').focus();
                return false;
            }

            if (address.postal_code !== '' && !Utils.validPostalCode(address.postal_code) ) {
                motify.log('邮政编码格式不正确');
                self.modalEle.find('input[name="postal_code"]').focus();
                return false;
            }
            if (!address.tel) {
                motify.log('请填写联系电话');
                self.modalEle.find('input[name="tel"]').focus();
                return false;
            }
            if (!Utils.validMobile(address.tel) && !Utils.validPhone(address.tel)) {
                motify.log('请填写正确的<br />手机号码或电话号码');
                self.modalEle.find('input[name="tel"]').focus();
                return false;
            }
            return true;
        },

        cancelEdit: function() {
            var self = this;

            Utils.needConfirm('确定要放弃此次编辑', function() {
                self.switchScene('address-list');
            }, function() {

            });
        },

        initCoupon: function() {
      /*      var self = this;

            var currentCoupon = global.current_card,
                availableCoupons = global.available_cards;

            var orderState = self.settings.orderState;
            if (orderState === 1 || orderState === 2) {

                if (availableCoupons.length > 1) {
                    self.autoUseCoupon(availableCoupons[1]);
                }

                // 绑定更换优惠券事件
                self.bodyEle.on('touchstart', '.js-change-coupon', function(event) {
                    event.preventDefault();

                    var ele = $(this);
                    var couponId = '' + ele.data('coupon-id');
                    self.showCoupons(couponId);
                });

                self.initCouponChoose();
            } else if (orderState === 3) {
                if (currentCoupon.card.id !== '0') {

                    self.useCoupon(currentCoupon);
                    $('.js-change-coupon').hide();

                }
            }*/

        },

        initCouponChoose: function() {
            var self = this;

            self.modalEle.on('tap', '.js-coupon-item', function(event) {
                event.preventDefault();

                var ele = $(this);
                var radio = ele.find('.radio');
                radio.prop('checked', true);

                var couponData = ele.data('coupon');

                console.log('coupon change: ', JSON.stringify(couponData));
                if (typeof couponData === 'string') {
                    couponData = $.parseJSON(couponData);
                }
                self.useCouponFx(couponData);

                self.hideModal();
            });
        },

        useCoupon: function(coupon) {
            var self = this;

            self.updateCoupon(coupon);

            var couponId = coupon.card.id;
            global.couponId = couponId;
        },

        useCouponFx: function(coupon) {
            var self = this;

            self.useCoupon(coupon);

            self.updateTotal(coupon.order);

            Utils.flashAnimate(self.useCouponEle.find('.order-module'));
            Utils.flashAnimate(self.orderTotalEle);
        },

        updateCoupon: function(coupon) {
            var self = this;

            var _html = '';
            if (!coupon) {
                return false;
            }

            var _available = 0;
            if (global.available_cards) {
                _available = global.available_cards.length - 1;
            }

            if (coupon.card.id !== '0') {
                _html = self.useCouponTpl(coupon);
            } else {
                _html = self.availableCouponTpl({
                    available: _available
                });
            }
            self.useCouponEle.html(_html).show();
        },

        updateTotal: function(order) {
            var self = this;

            var _html = self.orderTotalTpl({order: order, ump: global.ump});
            self.orderTotalEle.html(_html);
        },

        renderCouponList: function(couponId) {
            var self = this;

            var list = global.available_cards;

            if (list.length > 1) {
                self.couponContainer.empty();
                _(list).each(function(coupon, index, list) {

                    var item = $(self.couponItemTpl(coupon));
                    if (coupon.card && couponId === coupon.card.id) {
                        item.find('input.radio').prop('checked', true);
                    }

                    item.data('coupon', JSON.stringify(coupon));
                    self.couponContainer.append(item);
                });
            }
            self.initCouponFlag = true;
        },

        showSelectdCoupon: function(couponId) {
            var self = this;

            self.couponContainer.find('#coupon-', couponId).prop('checked', true);
            // self.initCouponChoose();
        }

    };

    window.app = window.app || new Klass();

})($, window, document);
